package com.twj.tools.poi;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @author 作者: tianwenju
 * @version 1.0
 * @project 金税三期工程核心征管及应用总集成项目
 * @package com.twj.tools.poi
 * @file T0.java 创建时间:2025年08月06日 15:34
 * @title 使用命令行方式将Word文档转换为PDF
 * @description 通过LibreOffice命令行工具将Word文档转换为PDF，并处理修订内容
 * @copyright Copyright (c) 2020 中国软件与技术服务股份有限公司
 * @company 中国软件与技术服务股份有限公司
 */
public class T0 {

    //LibreOffice的安装路径（如果环境变量已经配置，则不需要此路径）
    private static final String LIBREOFFICE_PATH = "C:\\Program Files\\LibreOffice\\program\\soffice.exe";
    private static String OS_NAME = "os.name";
    private static String WINDOWS = "windows";

    public static void main(String[] args) {
        String inputFilePath = "C:\\Users\\t1318\\Desktop\\税务\\供要管用\\222.doc";
        String outputFilePath = "C:\\Users\\t1318\\Desktop\\税务\\供要管用\\222.pdf";

        convertWordToPdfWithoutRevisions(inputFilePath, outputFilePath);
    }

    /**
     * 使用LibreOffice命令行将Word文档转换为PDF，接受所有修订并隐藏修订痕迹
     *
     * @param inputFilePath  输入的Word文档路径
     * @param outputFilePath 输出的PDF文件路径
     */
    public static void convertWordToPdfWithoutRevisions(String inputFilePath, String outputFilePath) {
        File inputFile = new File(inputFilePath);
        File outputFile = new File(outputFilePath);

        if (!inputFile.exists()) {
            System.err.println("Input file does not exist: " + inputFilePath);
            return;
        }

        boolean IS_WINDOWS = System.getProperty(OS_NAME).toLowerCase().contains(WINDOWS);

        // 构建LibreOffice命令行指令
        StringBuilder command = new StringBuilder();
        if (IS_WINDOWS && LIBREOFFICE_PATH != null && !LIBREOFFICE_PATH.isEmpty()) {
            command.append("\"").append(LIBREOFFICE_PATH).append("\" --headless ");
        } else {
            command.append("libreoffice --headless ");
        }

        // 添加接受所有修订的参数
        command.append("--accept-all-changes ");

        // 添加PDF导出选项，确保不显示修订痕迹
        command.append("--convert-to \"pdf:writer_pdf_Export:{");
        command.append("\\\"ExportBookmarks\\\":true,");
        command.append("\\\"ExportBookmarksToPDFDestination\\\":true,");
        command.append("\\\"ExportFormFields\\\":true,");
        command.append("\\\"HideViewerToolbar\\\":false,");
        command.append("\\\"HideViewerMenubar\\\":false,");
        command.append("\\\"HideViewerWindowControls\\\":false,");
        command.append("\\\"FitWindow\\\":false,");
        command.append("\\\"CenterWindow\\\":false,");
        command.append("\\\"OpenBookmarkLevels\\\":-1,");
        command.append("\\\"PrintChanges\\\":false,");  // 不打印修订
        command.append("\\\"PrintAnnotations\\\":false,");  // 不打印批注
        command.append("\\\"ExportTrackedChanges\\\":false,");  // 不导出跟踪更改
        command.append("\\\"ShowTrackedChanges\\\":false");  // 不显示跟踪更改
        command.append("}\" ");

        // 指定输出目录
        command.append("--outdir \"").append(outputFile.getParent()).append("\" ");

        // 指定输入文件
        command.append("\"").append(inputFilePath).append("\"");

        try {
            System.out.println("执行命令: " + command.toString());

            // 执行系统命令
            Process process = Runtime.getRuntime().exec(command.toString());

            // 读取命令执行的输出流
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println("输出: " + line);
            }

            // 读取命令执行的错误流
            BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            while ((line = errorReader.readLine()) != null) {
                System.err.println("错误: " + line);
            }

            // 等待进程结束
            int exitCode = process.waitFor();
            if (exitCode == 0) {
                System.out.println("转换成功: " + outputFilePath);
            } else {
                System.err.println("转换失败，退出码: " + exitCode);
            }

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 简化版本的转换方法（使用基本参数）
     *
     * @param inputFilePath  输入的Word文档路径
     * @param outputFilePath 输出的PDF文件路径
     */
    public static void convertWordToPdfSimple(String inputFilePath, String outputFilePath) {
        File inputFile = new File(inputFilePath);

        if (!inputFile.exists()) {
            System.err.println("Input file does not exist: " + inputFilePath);
            return;
        }

        boolean IS_WINDOWS = System.getProperty(OS_NAME).toLowerCase().contains(WINDOWS);

        // 构建LibreOffice命令行指令
        StringBuilder command = new StringBuilder();
        if (IS_WINDOWS && LIBREOFFICE_PATH != null && !LIBREOFFICE_PATH.isEmpty()) {
            command.append("\"").append(LIBREOFFICE_PATH).append("\" --headless ");
        } else {
            command.append("libreoffice --headless ");
        }

        // 使用accept-all-changes参数接受所有修订
        command.append("--accept-all-changes ");

        // 简单的PDF转换
        command.append("--convert-to pdf ");

        // 指定输出目录
        command.append("--outdir \"").append(new File(outputFilePath).getParent()).append("\" ");

        // 指定输入文件
        command.append("\"").append(inputFilePath).append("\"");

        try {
            System.out.println("执行命令: " + command.toString());

            // 执行系统命令
            Process process = Runtime.getRuntime().exec(command.toString());

            // 读取输出和错误流
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));

            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println("输出: " + line);
            }

            while ((line = errorReader.readLine()) != null) {
                System.err.println("错误: " + line);
            }

            // 等待进程结束
            int exitCode = process.waitFor();
            if (exitCode == 0) {
                System.out.println("转换成功: " + outputFilePath);
            } else {
                System.err.println("转换失败，退出码: " + exitCode);
            }

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}
